package cn.edu.imust.loginregisterdemo.upload.view;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;
import cn.edu.imust.loginregisterdemo.R;
import cn.edu.imust.loginregisterdemo.base.BaseFragment;
import cn.edu.imust.loginregisterdemo.feedback.FeedBackAdapter;
import cn.edu.imust.loginregisterdemo.upload.Update;
import cn.edu.imust.loginregisterdemo.utils.GetGPSUtil;
import cn.edu.imust.loginregisterdemo.login.model.User;
import cn.edu.imust.loginregisterdemo.utils.ToBase64Util;
import cn.edu.imust.loginregisterdemo.utils.CheckPermissionUtils;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class UploadFragment extends BaseFragment implements EasyPermissions.PermissionCallbacks {


    /**
     * 选择系统图片Request Code
     */
    private static final int REQUEST_IMAGE       = 112;
    /**
     * 请求CAMERA权限码
     */
    private static final int REQUEST_CAMERA_PERM = 101;
    /**
     * 请求GPS权限码
     */
    private static final int REQUEST_GPS_PERM = 101;
    /**
     * 拍照回调请求码，根据自己的需求定义数值F
     */
    private static final int REQ_CODE_CAMERA     = 113;
/*    @BindView(R.id.iv_scan)
    ImageView    ivScan;
    @BindView(R.id.iv_select)
    ImageView    ivSelect;

    @BindView(R.id.delete)
    TextView       delete;
    @BindView(R.id.take_pic)
    TextView       takePic;
    @BindView(R.id.imgFbackAdd)
    ImageView    imgFbackAdd;*/
    @BindView(R.id.update_edit_edit)
    EditText editText;
    @BindView(R.id.update_gps_show)
    TextView textView_GPS;
    @BindView(R.id.update_time_show)
    TextView textView_Time;
    @BindView(R.id.update_pic_take)
    Button button;
    @BindView(R.id.update_pic_show)
    ImageView imageView;
    @BindView(R.id.update)
    Button update;
    //用来保存拍照时临时存储的uri
    private       Uri             imgUrl;
    // 相册
    private final int             REQ_CODE_PICTURE = 22;
    // 裁图
    private final int             REQ_CODE_CUT     = 23;
    private       GridView        gvFbackImg;
    private       FeedBackAdapter adapter;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption locationOption = null;
    //声明AMapLocationClient类对象
    private AMapLocationClient      locationClient = null;
    private StringBuffer sb;
    private String       operator = BmobUser.getCurrentUser(User.class).getUsername();

    private File currentImageFile = null;
    private File cropImageFile = null;
    private Bitmap bitmap;
    private String time;
    private String stringGPS;
    private static Context context;
    private boolean b;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_upload, container, false);
        sb = new StringBuffer();
        sb.append("操作人: " + operator +"            |   ");
        ButterKnife.bind(this, contentView);
        ZXingLibrary.initDisplayOpinion(getActivity());
        initPermission();
        //initMap();
        context = getActivity().getApplicationContext();
/*        ivScan.setOnClickListener(new ButtonOnClickListener(R.id.iv_scan));
        ivSelect.setOnClickListener(new ButtonOnClickListener(R.id.iv_select));
        iv_result.setOnClickListener(new ButtonOnClickListener(R.id.iv_result));*/
        imageView.setOnClickListener(new ButtonOnClickListener(R.id.update_pic_show));
        button.setOnClickListener(new ButtonOnClickListener(R.id.update_pic_take));
        update.setOnClickListener(new ButtonOnClickListener(R.id.update));
        getNetworkLocation();
        time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getNetTime());
        textView_Time.setText(time);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
/*        imgFbackAdd.setImageResource(R.drawable.default_pic);*/
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    /**
     * 初始化权限事件
     */
    private void initPermission() {
        //检查权限
        String[] permissions = CheckPermissionUtils.checkPermission(getActivity());
        if (permissions.length == 0) {
            //权限都申请了
            //是否登录
        } else {
            //申请权限
            ActivityCompat.requestPermissions(getActivity(), permissions, 100);
        }
    }

    private void initMap() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) {

            //初始化定位
            locationClient = new AMapLocationClient(getActivity());
            //设置定位回调监听
            locationClient.setLocationListener(mLocationListener);

            //初始化AMapLocationClientOption对象
            locationOption = new AMapLocationClientOption();

            //设置定位模式为高精度模式，AMapLocationMode.Battery_Saving为低功耗模式，AMapLocationMode.Device_Sensors是仅设备模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置是否返回地址信息（默认返回地址信息）
            locationOption.setNeedAddress(true);
            //设置是否只定位一次,默认为false
            locationOption.setOnceLocation(false);
            //设置是否强制刷新WIFI，默认为强制刷新
            locationOption.setWifiActiveScan(true);
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            locationOption.setMockEnable(false);
            //设置定位间隔,单位毫秒,默认为2000ms
            locationOption.setInterval(2000);
            startLocation();
        }else {
            EasyPermissions.requestPermissions(this, "需要请求GPS权限",
                    REQUEST_GPS_PERM, Manifest.permission.ACCESS_COARSE_LOCATION);

        }

    }

    //声明定位回调监听器
    private AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {

                if (aMapLocation.getErrorCode() == 0) {
/*                    sb.append("时间: " + Utils.formatUTC(aMapLocation.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                    sb.append("地    址: " + aMapLocation.getAddress() + "\n");*/

/*                    textView_GPS.setText(String.format("地    址: %s\n", aMapLocation.getAddress()));
                    textView_Time.setText(String.format("时间: %s\n", Utils.formatUTC(aMapLocation.getTime(), "yyyy-MM-dd HH:mm:ss")));*/

                    stopLocation();
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("info", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());

                }
            }
        }
    };

    private void startLocation() {
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    //销毁定位
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 1:
                //处理扫描结果（在界面上显示）
                ContentResolver contentResolver = this.getActivity().getContentResolver();
                try {
                    InputStream inputStream = contentResolver.openInputStream(Uri.fromFile(currentImageFile));
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 3;
                    bitmap = BitmapFactory.decodeStream(inputStream,null,options);
                    imageView.setImageBitmap(bitmap);
                    //imageView.setImageURI(Uri.fromFile(currentImageFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_IMAGE:
                ContentResolver contentResolver2 = this.getActivity().getContentResolver();
                try {
                    InputStream inputStream = contentResolver2.openInputStream(Uri.fromFile(cropImageFile));
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 3;
                    bitmap = BitmapFactory.decodeStream(inputStream, null, options);
                    imageView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NotNull String[] permissions, @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

/*
    @AfterPermissionGranted(REQUEST_CAMERA_PERM)
*/

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Toast.makeText(getActivity(), "执行onPermissionsGranted()...", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(getActivity(), "执行onPermissionsDenied()...", Toast.LENGTH_SHORT).show();
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "当前App需要申请camera权限,需要打开设置页面么?")
                    .setTitle("权限申请")
                    .setPositiveButton("确认")
                    .setNegativeButton("取消", null /* click listener */)
                    .setRequestCode(REQUEST_CAMERA_PERM)
                    .build()
                    .show();
        }
    }

    /**
     * 按钮点击监听
     */
    class ButtonOnClickListener implements View.OnClickListener {

        private int buttonId;

        public ButtonOnClickListener(int buttonId) {
            this.buttonId = buttonId;
        }

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.update:
                    Update up = new Update();
                    ToBase64Util toBase64Util = new ToBase64Util();
                    try {
                        b = up.httpPost(textView_Time.getText().toString(),textView_GPS.getText().toString(),editText.getText().toString(), toBase64Util.Bitmap2StrByBase64(bitmap),currentImageFile,cropImageFile);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (b){
                        Toast.makeText(getActivity(),"上传成功",Toast.LENGTH_SHORT).show();
                    }
                    else
                        Toast.makeText(getActivity(),"上传失败",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.update_pic_take:
                    if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA)) {
                        // Have permission, do the thing!

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                            StrictMode.setVmPolicy(builder.build());
                        }
                        //获取一个临时uri
                        File dir1 = new File(Environment.getExternalStorageDirectory(),"pictures");
                        if (dir1.exists()){
                            dir1.mkdirs();
                        }
                        currentImageFile = new File(dir1,System.currentTimeMillis() + ".jpg");
                        if (!currentImageFile.exists()){
                            try {
                                currentImageFile.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        //启动系统照相机
                        Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentImageFile));
                        startActivityForResult(intent1, 1);
                    } else {
                        // Ask for one permission
                        EasyPermissions.requestPermissions(this, "需要请求camera权限",
                                REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);
                    }
                    break;
                case R.id.update_pic_show:
                    File dir2 = new File(Environment.getExternalStorageDirectory(),"pictures");
                    if (dir2.exists()){
                        dir2.mkdirs();
                    }
                    cropImageFile = new File(dir2,System.currentTimeMillis() + ".jpg");
                    if (!cropImageFile.exists()){
                        try {
                            cropImageFile.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    Intent intent2 = new Intent("com.android.camera.action.CROP");
                    intent2.setDataAndType(Uri.fromFile(currentImageFile), "image/*");
                    intent2.putExtra("scale", true);
                    intent2.putExtra("return-data", false);//设置为不返回缩略图
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropImageFile));//设置大图保存到文件
                    intent2.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//保存的图片格式
                    intent2.putExtra("noFaceDetection", false);

                    startActivityForResult(intent2,REQUEST_IMAGE);

                    break;
            }

        }
    }
    public static Date getNetTime(){
        String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
        try {
            URL url = new URL(webUrl);
            URLConnection uc = url.openConnection();
            uc.setReadTimeout(5000);
            uc.setConnectTimeout(5000);
            uc.connect();
            long correctTime = uc.getDate();
            return new Date(correctTime);
        } catch (Exception e) {
            return new Date();
        }
    }
    private void getNetworkLocation() {
        if (!EasyPermissions.hasPermissions(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
            EasyPermissions.requestPermissions(this, "需要请求GPS权限",
                    REQUEST_GPS_PERM, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
        }
        Location net = GetGPSUtil.getNetWorkLocation(getContext());
        if (net == null) {
            Location gps = GetGPSUtil.getGPSLocation(getContext());
            if (gps == null){
                GetGPSUtil.addLocationListener(context, LocationManager.GPS_PROVIDER, location -> {
                    if (location != null) {
                        stringGPS = String.format("定位信息:\n纬度==%s\n经度==%s", location.getLatitude(), location.getLongitude());
                        textView_GPS.setText(stringGPS);
                    } else {
                        textView_GPS.setText("gps location is null");
                    }
                });
            }
        } else {
            stringGPS = String.format("定位信息:\n纬度==%s\n经度==%s", net.getLatitude(), net.getLongitude());
            textView_GPS.setText(stringGPS);
        }
    }

}
